package com.forlove.app.qselect.login.ui;

import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseTakePhotoActivity;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.widget.CircleImageView;
import com.forlove.app.manager.CustomHelper;
import com.forlove.app.manager.DataManager;
import com.forlove.app.manager.ServerManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.manager.async.LoadUserinfoAsync;
import com.forlove.app.qselect.friend.ui.AddFriendGuideActivity;
import com.forlove.app.qselect.login.entity.DataDto;
import com.forlove.app.qselect.login.entity.DataInfoEntity;
import com.forlove.app.qselect.login.entity.EmotionEntity;
import com.forlove.app.qselect.login.entity.GroupEntity;
import com.forlove.app.qselect.login.entity.ProvinceEntity;
import com.forlove.app.qselect.login.entity.SchoolDto;
import com.forlove.app.qselect.login.entity.SchoolInfoEntity;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.forlove.app.qselect.login.presenter.SetUserInfoPresenter;
import com.forlove.app.qselect.login.view.SetUserInfoView;
import com.forlove.app.qselect.login.widget.ChoicePictureDialog;
import com.forlove.app.qselect.login.widget.pickerview.OptionsPickerView;
import com.forlove.app.qselect.school.ui.SearchSchoolActivity;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

/**
 * 设置用户信息
 * Created by yjl on 2017/10/10.
 * version 1.01 屏蔽感情状态,增加邀请人id
 */

public class SetUserInfoActivity extends BaseTakePhotoActivity implements View.OnClickListener,
        LoaderManager.LoaderCallbacks<DataDto>, SetUserInfoView {
    private final int pos_sex = 1;
    private final int pos_group = 2;
    private final int pos_emotion = 3;
    private final int pos_city = 4;
    private final int pos_age = 5;
    private final int pos_school = 6;
    @BindView(R.id.view_user_info)
    LinearLayout view_user_info;//设置用户信息页面

    @BindView(R.id.bt_setinfo_next_step)
    TextView bt_setinfo_next_step;

    @BindView(R.id.input_real_name)
    AppCompatEditText input_real_name;

    @BindView(R.id.text_user_sex)
    TextView text_user_sex;

    @BindView(R.id.text_emotion)
    TextView text_emotion;

    @BindView(R.id.text_group)
    TextView text_group;

    @BindView(R.id.text_city)
    TextView text_city;

    @BindView(R.id.view_set_photo)
    CircleImageView view_set_photo;

    @BindView(R.id.text_school)
    TextView text_school;
    //    @BindView(R.id.text_account)
//    TextView text_account;
    @BindView(R.id.input_invite_friend_id)
    AppCompatEditText input_invite_friend_id;

    private LoadUserinfoAsync loadUserinfoAsync;
    private SetUserInfoPresenter setUserInfoPresenter;
    private OptionsPickerView pvOptions;
    private OptionsPickerView sexOptions;
    private List<ProvinceEntity> provinceEntities = new ArrayList<>();
    private List<List<DataInfoEntity>> cityname = new ArrayList<>();
    private List<EmotionEntity> emotionEntities = new ArrayList<>();
    private List<List<DataInfoEntity>> childEmotion = new ArrayList<>();
    private List<GroupEntity> groupEntities = new ArrayList<>();
    private List<List<DataInfoEntity>> childTag = new ArrayList<>();
    private Map<Integer, SchoolInfoEntity> schoolMap = new HashMap<>(); //学校
    private List<SchoolInfoEntity> schoolInfoEntities = new ArrayList<>();
    private List<List<String>> yuanxi = new ArrayList<>();  //院系
    private String realName;
    private List<String> sexList = new ArrayList<>();
    private int sex = -1;
    private int option = 0;
    private int groupId = -1;
    private int emotionId = -1;
    private int cityId = -1;
    private String inviteID = "";//邀请人id
    private UserEntity userEntity;
    private String photoPath = "";
    private String tempPhoto = "";
    private boolean setPhotoResult = false;
    private ChoicePictureDialog choicePictureDialog;
    private String mYx;  //院系
    private int schoolId;//学校
    private SchoolInfoEntity selectSchool;
    private HandlerThread handlerThread;
    private Handler handler;

    @Override
    public int getLayoutId() {
        return R.layout.activity_set_userinfo;
    }

    @Override
    public void initView() {
        setUserInfoPresenter = new SetUserInfoPresenter(this);
        setPresenter(setUserInfoPresenter);
        setCanBack(false);
        getSupportLoaderManager().restartLoader(LoadUserinfoAsync.ASYNC_ID, null, this);
        bt_setinfo_next_step.setOnClickListener(this);
        text_user_sex.setOnClickListener(this);
        text_emotion.setOnClickListener(this);
        text_group.setOnClickListener(this);
        text_city.setOnClickListener(this);
        view_set_photo.setOnClickListener(this);
        text_school.setOnClickListener(this);
        updateNextStep();
        initPickerView();
        sexList.add("男生");
        sexList.add("女生");
        loadSchoolCache();
        input_real_name.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                realName = s.toString().replaceAll(" ", "");
                if (realName.length() > 16) {
                    Toast.makeText(SetUserInfoActivity.this, "真实姓名不得多于16个字符！", Toast.LENGTH_SHORT).show();
                }
                if (StringUtils.isNotEmpty(realName)) {
                    input_real_name.setHint(null);
                }
            }
        });
        input_real_name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String str = input_real_name.getText().toString();
                if (hasFocus) {
                    // 获得焦点
                    if (StringUtils.isNotEmpty(str)) {
                        input_real_name.setSelection(str.length());
                    } else {
                        input_real_name.setHint(null);
                    }
                } else {
                    // 失去焦点
                    if (!StringUtils.isNotEmpty(str)) {
                        input_real_name.setHint("真实姓名");
                    }
                }
            }
        });
        userEntity = UserManager.getUesrInfo(this);
        if (userEntity != null && !TextUtils.isEmpty(userEntity.mUserImage)) {
            setUserInfoPresenter.loadImageView(this,
                    view_set_photo, userEntity.mUserImage,
                    R.mipmap.image_mine_friend_avatar);
        }
        if (StringUtils.isNotEmpty(userEntity.realname)) {
            input_real_name.setText(userEntity.realname);
            input_real_name.setEnabled(false);
            realName = userEntity.realname;
        }
        ClipboardManager mClipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        if (mClipboardManager != null
                && !TextUtils.isEmpty(mClipboardManager.getText())) {
            String clipData = mClipboardManager.getText().toString();
            //TODO
            if (StringUtils.isNotEmpty(clipData) && clipData.startsWith("username_inv")) {
                String invitID = clipData.substring("username_inv".length() + 1, clipData.length());
                if (StringUtils.isNotEmpty(invitID)) {
                    input_invite_friend_id.setText(invitID);
                }
            }
        }

        input_invite_friend_id.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                String str = input_invite_friend_id.getText().toString();
                if (hasFocus) {
                    // 获得焦点
                    if (StringUtils.isNotEmpty(str)) {
                        input_invite_friend_id.setSelection(str.length());
                    } else {
                        input_invite_friend_id.setHint(null);
                    }
                } else {
                    // 失去焦点
                    if (!StringUtils.isNotEmpty(str)) {
                        input_invite_friend_id.setHint("邀请人ID");
                    }
                }
            }
        });
        input_invite_friend_id.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString();
                inviteID = str;
                if (StringUtils.isNotEmpty(str)) {
                    input_invite_friend_id.setHint(null);
                }
            }
        });
    }

    private void loadSchoolCache() {
        if (handlerThread == null) {
            handlerThread = new HandlerThread("loadschool");
            handlerThread.start();
        }
        if (handler == null) {
            handler = new Handler(handlerThread.getLooper());
        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                String school = DataManager.getSchoolInfo();
                if (StringUtils.isNotEmpty(school)) {
                    SchoolDto schoolDto = JSON.parseObject(school, SchoolDto.class);
                    if (schoolDto != null && schoolDto.getData() != null) {
                        schoolMap.clear();
                        schoolMap.putAll(schoolDto.getData());
                    }
                }
                schoolInfoEntities.clear();
                schoolInfoEntities.addAll(DataManager.parseSchool(schoolMap));
                yuanxi.clear();
                for (SchoolInfoEntity schoolInfoEntity : schoolInfoEntities) {
                    yuanxi.add(schoolInfoEntity.getAcademic());
                }
                setUserInfoPresenter.loadSchoolInfo();
            }
        });
    }

    private void requestUpdateUserInfo() {
        if (TextUtils.isEmpty(realName)) {
            Toast.makeText(this, "真实姓名不可为空!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!StringUtils.checkChinese(realName)) {
            Toast.makeText(this, "真实姓名必须为中文！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (realName.length() < 2 && realName.length() > 16) {
            Toast.makeText(SetUserInfoActivity.this, "真实姓名不得少于2个或者多于16个字符！", Toast.LENGTH_SHORT).show();
            return;
        }
        if (sex < 0) {
            Toast.makeText(this, "请选择性别!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (groupId < 0) {
            Toast.makeText(this, "请设置身份信息!", Toast.LENGTH_SHORT).show();
            return;
        }
//        if (emotionId < 0) {
//            Toast.makeText(this, "请选择感情状态!", Toast.LENGTH_SHORT).show();
//            return;
//        }
        if (groupId >= 10100 && groupId <= 10109) {
            if (schoolId <= 0) {
                Toast.makeText(this, "请选择学校!", Toast.LENGTH_SHORT).show();
                return;
            }
            if (!StringUtils.isNotEmpty(mYx)) {
                Toast.makeText(this, "请选择专业!", Toast.LENGTH_SHORT).show();
                return;
            }

        }
//        if (cityId < 0) {
//            Toast.makeText(this, "请选择城市地址!", Toast.LENGTH_SHORT).show();
//            return;
//        }
        this.userEntity.realname = realName;
        this.userEntity.mSex = this.sex;
        this.userEntity.scholar = groupId;//年级
//        this.userEntity.issingle = emotionId;//感情状态先屏蔽
//        this.userEntity.address = cityId;
        if (!StringUtils.isNotEmpty(userEntity.birthday)) {
            String birth = UserManager.getUserAge(this);
            this.userEntity.birthday = birth;
        }
        this.userEntity.school = schoolId;
        this.userEntity.yuanxi = mYx;
        setUserInfoPresenter.loadUpdateUserinfoData(this.userEntity, inviteID);
    }

    private void requestUplaodeImage() {
        if (TextUtils.isEmpty(photoPath)) {
            return;
        }
        Map param = new HashMap();
        param.put("Filedata", photoPath);
        setUserInfoPresenter.upLoadPic(param);

    }

    private boolean updateNextStep() {
        if (!TextUtils.isEmpty(realName)
                && sex > 0 && groupId > 0
                && emotionId > 0) {
            bt_setinfo_next_step.setBackground(getResources().getDrawable(R.drawable.bt_nextstep_selector));
            return true;
        } else {
            bt_setinfo_next_step.setBackground(getResources().getDrawable(R.drawable.bg_blue_nextstep_corner_sel));
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_setinfo_next_step:
                if (!setPhotoResult) {
                    requestUplaodeImage();
                }
                requestUpdateUserInfo();
                break;
            case R.id.text_user_sex:
                option = pos_sex;
                sexOptions.setTitleText("性别");
                sexOptions.setPicker(sexList);
                sexOptions.show();
                break;
            case R.id.text_group:
                if (groupEntities.size() > 0 && childTag.size() > 0) {
                    pvOptions.setTitleText("我的年级");
                    pvOptions.setPicker(groupEntities, this.childTag);
                    pvOptions.show();
                    option = pos_group;
                }
                break;

            case R.id.text_emotion:
                if (emotionEntities.size() > 0 && childEmotion.size() > 0) {
                    pvOptions.setTitleText("婚恋状态");
                    pvOptions.setPicker(emotionEntities, this.childEmotion);
                    pvOptions.show();
                    option = pos_emotion;
                }
                break;
            case R.id.text_city:
                if (provinceEntities.size() > 0 && cityname.size() > 0) {
                    pvOptions.setTitleText("所在地区");
                    pvOptions.setPicker(provinceEntities, cityname);
                    pvOptions.show();
                    option = pos_city;
                }
                break;

            case R.id.view_set_photo:
                setPhoto();
                break;
            case R.id.text_school:
                //TODO 选择学校
//                if (schoolInfoEntities.size() > 0 && yuanxi.size() > 0) {
//                    pvOptions.setTitleText("我的学校");
//                    pvOptions.setPicker(schoolInfoEntities, yuanxi);
//                    pvOptions.show();
//                    option = pos_school;
//                }
                Intent intent = new Intent(this, SearchSchoolActivity.class);
                startActivityForResult(intent, SearchSchoolActivity.request_from_set_info);
                break;
        }
    }

    private void setPhoto() {

        final CropOptions cropOptions = CustomHelper.getCustomHelper().getCropOptions();
        final Uri imageUri = CustomHelper.getCustomHelper().getURI(getTakePhoto());//保存的路径
        if (choicePictureDialog == null) {
            choicePictureDialog = new ChoicePictureDialog(this);
            choicePictureDialog.choiceCameraPicture(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                getTakePhoto().onPickFromCapture(imageUri);//不裁剪
                    getTakePhoto().onPickFromCaptureWithCrop(imageUri, cropOptions);
                }
            });
            choicePictureDialog.choiceGallertPictire(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //从相册中获取图片
                    getTakePhoto().onPickFromGalleryWithCrop(imageUri, cropOptions);
                }
            });
        }
        if (!choicePictureDialog.isShowing()) {
            choicePictureDialog.show();
        }
    }

    private LoadUserinfoAsync createUserinfoAsync() {
        if (loadUserinfoAsync == null) {
            loadUserinfoAsync = new LoadUserinfoAsync(this);
        }
        return loadUserinfoAsync;
    }

    @Override
    public Loader<DataDto> onCreateLoader(int id, Bundle args) {
        return createUserinfoAsync();
    }

    @Override
    public void onLoaderReset(Loader<DataDto> loader) {

    }

    @Override
    public void onLoadFinished(Loader<DataDto> loader, DataDto data) {
        getSupportLoaderManager().destroyLoader(LoadUserinfoAsync.ASYNC_ID);
        if (data.getCitys() != null) {
            initProvinceData(data.getCitys());
        }

        if (data.getEmotion() != null) {
            initEmotionData(data.getEmotion());
        }

        if (data.getGroup() != null) {
            initGroupData(data.getGroup());
        }
    }

    public void hideKeyboard(View v) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
        }
    }

    private void initGroupData(Map<String, DataInfoEntity> groups) {
        ArrayList<DataInfoEntity> parenGroup = new ArrayList<>();
        ArrayList<DataInfoEntity> childGroup = new ArrayList<>();
        for (String key : groups.keySet()) {
            DataInfoEntity group = groups.get(key);
            if (group.parentid == 0) {
                parenGroup.add(group);
            } else {
                childGroup.add(group);
            }
        }
        groupEntities.clear();
        childTag.clear();
        for (DataInfoEntity parentG : parenGroup) {
            GroupEntity groupEntity = new GroupEntity();
            groupEntity.mGroup = parentG;
            for (DataInfoEntity childG : childGroup) {
                if (childG.parentid == parentG.id) {
                    groupEntity.childTag.add(childG);
                }
            }
            groupEntities.add(groupEntity);
            childTag.add(groupEntity.childTag);
        }

    }

    private void initEmotionData(Map<String, DataInfoEntity> emotion) {
        ArrayList<DataInfoEntity> parentEmotion = new ArrayList<>();
        ArrayList<DataInfoEntity> childEmotion = new ArrayList<>();
        for (String key : emotion.keySet()) {
            DataInfoEntity childemotion = emotion.get(key);
            if (childemotion.parentid == 0) {
                parentEmotion.add(childemotion);
            } else {
                childEmotion.add(childemotion);
            }
        }
        emotionEntities.clear();
        this.childEmotion.clear();
        for (DataInfoEntity parent : parentEmotion) {
            EmotionEntity emotionEntity = new EmotionEntity();
            emotionEntity.emotion = parent;
            for (int i = 0; i < childEmotion.size(); i++) {
                DataInfoEntity child = childEmotion.get(i);
                if (child.parentid == parent.id) {
                    emotionEntity.dataInfoEntities.add(child);
                }
            }
            emotionEntities.add(emotionEntity);
            this.childEmotion.add(emotionEntity.dataInfoEntities);
        }
        if (pvOptions == null) {
            initPickerView();
        }
    }

    private void initProvinceData(Map<String, DataInfoEntity> mCitys) {
        ArrayList<DataInfoEntity> province = new ArrayList<>();
        ArrayList<DataInfoEntity> cityEntities = new ArrayList<>();
        for (String key : mCitys.keySet()) {
            DataInfoEntity cityEntity = mCitys.get(key);
            if (cityEntity.parentid == 0) {
                province.add(cityEntity);
            } else {
                cityEntities.add(cityEntity);
            }
        }

        provinceEntities.clear();
        cityname.clear();
        for (DataInfoEntity procity : province) {
            ProvinceEntity provinceEntity = new ProvinceEntity();
            provinceEntity.province = procity;
            for (int i = 0; i < cityEntities.size(); i++) {
                DataInfoEntity cityEntity = cityEntities.get(i);
                if (cityEntity.parentid == procity.id) {
                    provinceEntity.cityEntities.add(cityEntity);
                }
            }
            this.provinceEntities.add(provinceEntity);
            cityname.add(provinceEntity.cityEntities);
        }

    }

    private void initPickerView() {
        if (pvOptions == null) {
            pvOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    //返回的分别是三个级别的选中位置
                    switch (option) {
                        case pos_group:
                            DataInfoEntity group = groupEntities.get(options1).getChildTag().get(options2);
                            String groupStr = groupEntities.get(options1).getPickerViewText() + " - "
                                    + group.getName();
                            text_group.setText(groupStr);
                            groupId = group.id;
                            if (groupId >= 10100 && groupId <= 10109) {
                                text_school.setVisibility(View.VISIBLE);
                            } else {
                                text_school.setVisibility(View.GONE);
                            }

                            break;
                        case pos_emotion:
                            DataInfoEntity emotion = emotionEntities.get(options1).getDataInfoEntities().get(options2);
                            String emotionStr = emotionEntities.get(options1).getPickerViewText() + " - " + emotion.getPickerViewText();
                            text_emotion.setText(emotionStr);
                            emotionId = emotion.id;
                            break;
                        case pos_city:
                            DataInfoEntity cityinfo = provinceEntities.get(options1).cityEntities.get(options2);
                            String cityname = provinceEntities.get(options1).getPickerViewText() + " - " + cityinfo.getPickerViewText();
                            text_city.setText(cityname);
                            cityId = cityinfo.id;
                            break;
                        case pos_school:
                            SchoolInfoEntity schoolInfoEntity = schoolInfoEntities.get(options1);
                            selectSchool = schoolInfoEntity;
                            schoolId = selectSchool.id;
                            mYx = schoolInfoEntity.getAcademic().get(options2);
                            text_school.setText(schoolInfoEntity.getSchool() + " - " + mYx);
//                            schoolOp1 = options1;
//                            schoolOp2 = options2;
                            break;
                    }
                    updateNextStep();

                }
            }).setDividerColor(getResources().getColor(R.color.common_line))
                    .setTextColorCenter(getResources().getColor(R.color.str_color_black))
                    .setCancelColor(getResources().getColor(R.color.common_green))
                    .setSubmitColor(getResources().getColor(R.color.common_green))
                    .setSubCalSize(14)
                    .setContentTextSize(14)
                    .setLineSpacingMultiplier(2f)
                    .setTitleSize(14)
                    .setOutSideCancelable(false)
                    .build();
        }
//        pvOptions.show();

        if (sexOptions == null) {
            sexOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
                @Override
                public void onOptionsSelect(int options1, int options2, int options3, View v) {
                    //返回的分别是三个级别的选中位置
                    switch (option) {
                        case pos_sex:
                            //1男2女
                            if (options1 == 0) {
                                sex = 1;
                            } else if (options1 == 1) {
                                sex = 2;
                            }
                            text_user_sex.setText(sexList.get(options1));
                            break;
                    }
                    updateNextStep();

                }
            }).setDividerColor(getResources().getColor(R.color.common_line))
                    .setTextColorCenter(getResources().getColor(R.color.str_color_black))
                    .setCancelColor(getResources().getColor(R.color.common_green))
                    .setSubmitColor(getResources().getColor(R.color.common_green))
                    .setSubCalSize(14)
                    .setContentTextSize(14)
                    .setLineSpacingMultiplier(2f)
                    .setTitleSize(14)
                    .setOutSideCancelable(false)
                    .build();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SearchSchoolActivity.request_from_set_info
                && resultCode == Activity.RESULT_OK) {
            selectSchool = (SchoolInfoEntity) data.getSerializableExtra("school");
            mYx = data.getStringExtra("yuanxi");
            text_school.setText(selectSchool.getSchool() + " - " + mYx);
            schoolId = selectSchool.getId();
        }
    }

    @Override
    public void updateUserinfoView(UserEntity userEntity) {
        if (userEntity != null) {
            this.userEntity.updateUserEntity(userEntity);
            UserManager.saveUserInfo(this, this.userEntity);
            Toast.makeText(this, "设置成功！", Toast.LENGTH_SHORT).show();
            //跳转添加好友提示页
            Intent intent = new Intent(this, AddFriendGuideActivity.class);
            startActivity(intent);
            this.finish();
//            Intent intent = new Intent(this, MainActivity.class);
//            Bundle bundle = new Bundle();
//            bundle.putInt(MainActivity.Key_Comefrom, MainActivity.COME_FROM_REGISTER);
//            intent.putExtras(bundle);
//            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//            startActivity(intent);
        }
    }

    @Override
    public void updateSetPhotoView(String photoUrl) {
        if (!TextUtils.isEmpty(photoUrl)) {
            setPhotoResult = true;
            userEntity.mUserImage = photoUrl;
            UserManager.saveUserInfo(this, userEntity);
            setUserInfoPresenter.clearImageCache(ServerManager.getImageUrl() + photoUrl);
            Toast.makeText(this, "头像设置成功!", Toast.LENGTH_SHORT).show();
            try {
                File photo = new File(photoPath);
                if (photo.exists()) {
                    photo.delete();
                }
                File tempFile = new File(tempPhoto);
                if (tempFile.exists()) {
                    tempFile.delete();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onDestroy() {
        getSupportLoaderManager().destroyLoader(LoadUserinfoAsync.ASYNC_ID);
        if (choicePictureDialog != null) {
            choicePictureDialog.dismiss();
            choicePictureDialog = null;
        }
        super.onDestroy();
    }


    @Override
    public void takeSuccess(final TResult result) {
        if (result != null && result.getImage() != null) {
            if (choicePictureDialog != null) {
                choicePictureDialog.dismiss();
            }
            photoPath = result.getImage().getCompressPath();
            tempPhoto = result.getImage().getOriginalPath();
            final Bitmap bitmap = BitmapFactory.decodeFile(photoPath);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    view_set_photo.setImageBitmap(bitmap);
                }
            });
            requestUplaodeImage();
        }
    }

    @Override
    public void takeFail(TResult result, String msg) {
        if (choicePictureDialog != null) {
            choicePictureDialog.dismiss();
        }
    }

    @Override
    public void takeCancel() {
        if (choicePictureDialog != null) {
            choicePictureDialog.dismiss();
        }
    }

    @Override
    public void updateSchoolInfo(Map<Integer, SchoolInfoEntity> school) {
        if (school != null && !school.isEmpty()) {
            this.schoolMap.clear();
            this.schoolMap.putAll(school);
            schoolInfoEntities.clear();
            schoolInfoEntities.addAll(DataManager.parseSchool(schoolMap));
            yuanxi.clear();
            for (SchoolInfoEntity schoolInfoEntity : schoolInfoEntities) {
                yuanxi.add(schoolInfoEntity.getAcademic());
            }
        }
    }
}
